package sea.plot;

import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import sea.util.PublicParam;
import sea.util.SimHyAHelper;
import sea.util.WinHelper;
import simhya.script.ExploredSymbol;

/**
 *
 * This class builds the layout of Deterministic Form of Plot
 * 
 * @author  Zhirun Ding
 * 
 * Created on 05/07/2012
 * 
 */

public class PlotDetermForm extends javax.swing.JDialog {
    
    /** Creates new form PlotDetermForm */
    public PlotDetermForm(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        simulationvarsList = new javax.swing.JList();
        selectAllButton = new javax.swing.JButton();
        deselectButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        finalStateRadioButton = new javax.swing.JRadioButton();
        timeRadioButton = new javax.swing.JRadioButton();
        givenTimeText = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        fixlistTable = new javax.swing.JTable();
        backButton = new javax.swing.JButton();
        confirmButton = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        exploredparamsList = new javax.swing.JList();
        addfixButton = new javax.swing.JButton();
        helpButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sea.SimHyAGui.class).getContext().getResourceMap(PlotDetermForm.class);
        setTitle(resourceMap.getString("PlotDetermForm.title")); // NOI18N
        setName("PlotDetermForm"); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        simulationvarsList.setName("simulationvarsList"); // NOI18N
        jScrollPane1.setViewportView(simulationvarsList);

        selectAllButton.setText(resourceMap.getString("selectAllButton.text")); // NOI18N
        selectAllButton.setName("selectAllButton"); // NOI18N
        selectAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectAllButtonActionPerformed(evt);
            }
        });

        deselectButton.setText(resourceMap.getString("deselectButton.text")); // NOI18N
        deselectButton.setName("deselectButton"); // NOI18N
        deselectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deselectButtonActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jPanel1.setName("jPanel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        finalStateRadioButton.setSelected(true);
        finalStateRadioButton.setText(resourceMap.getString("finalStateRadioButton.text")); // NOI18N
        finalStateRadioButton.setName("finalStateRadioButton"); // NOI18N
        finalStateRadioButton.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                finalStateRadioButtonItemStateChanged(evt);
            }
        });

        timeRadioButton.setText(resourceMap.getString("timeRadioButton.text")); // NOI18N
        timeRadioButton.setName("timeRadioButton"); // NOI18N
        timeRadioButton.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                timeRadioButtonItemStateChanged(evt);
            }
        });

        givenTimeText.setText(resourceMap.getString("givenTimeText.text")); // NOI18N
        givenTimeText.setEnabled(false);
        givenTimeText.setName("givenTimeText"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(timeRadioButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(givenTimeText, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(finalStateRadioButton))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(finalStateRadioButton)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(timeRadioButton)
                    .addComponent(givenTimeText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(11, Short.MAX_VALUE))
        );

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        fixlistTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Selected", "Name", "Value"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        fixlistTable.setName("fixlistTable"); // NOI18N
        jScrollPane2.setViewportView(fixlistTable);

        backButton.setText(resourceMap.getString("backButton.text")); // NOI18N
        backButton.setName("backButton"); // NOI18N
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });

        confirmButton.setText(resourceMap.getString("confirmButton.text")); // NOI18N
        confirmButton.setName("confirmButton"); // NOI18N
        confirmButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmButtonActionPerformed(evt);
            }
        });

        jLabel4.setForeground(resourceMap.getColor("jLabel4.foreground")); // NOI18N
        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        exploredparamsList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        exploredparamsList.setName("exploredparamsList"); // NOI18N
        exploredparamsList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                exploredparamsListMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(exploredparamsList);

        addfixButton.setText(resourceMap.getString("addfixButton.text")); // NOI18N
        addfixButton.setName("addfixButton"); // NOI18N
        addfixButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addfixButtonActionPerformed(evt);
            }
        });

        helpButton.setText(resourceMap.getString("helpButton.text")); // NOI18N
        helpButton.setName("helpButton"); // NOI18N
        helpButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                helpButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(deselectButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(selectAllButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(37, 37, 37)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(addfixButton)))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel4))
                        .addGap(37, 37, 37)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(33, 33, 33)
                        .addComponent(confirmButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(helpButton)
                        .addGap(22, 22, 22))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(1, 1, 1)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(addfixButton))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(selectAllButton)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(deselectButton)
                    .addComponent(confirmButton)
                    .addComponent(helpButton)
                    .addComponent(backButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
        this.setVisible(false);
        
        if (PublicParam.PreviousForm != null) {
            PublicParam.PreviousForm.setVisible(true);
        }    
    }//GEN-LAST:event_backButtonActionPerformed

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        if (PublicParam.PreviousForm != null) {
            PublicParam.PreviousForm.setVisible(false);
        }
        
        //get data variables
        String datavar = ((PlotForm)PublicParam.PlotForm).getCurrentDataVariable();
        if (lastDataVariable.equals(datavar)) return;//no change
        lastDataVariable = datavar;
        
        //get parameter by data variable
        ArrayList<simhya.script.Symbol> vars = PublicParam.SimHyACommand.getVariables(datavar);
        
        //1.init vars list
        WinHelper.initListbox(simulationvarsList, vars);
        //default select all
        WinHelper.setListSelectall(simulationvarsList, "time");
        
        //2.init fixlist
        ArrayList<ExploredSymbol> evars = PublicParam.SimHyACommand.getExploredParameters(datavar);
        WinHelper.initTable(fixlistTable, evars);
        //3.init explored prams
        WinHelper.initListbox3(exploredparamsList, evars);
        
        //disabled given time if explored variable does not constain trajectory data.
        if (PublicParam.SimHyACommand.exploratorVariableContainsTrajectoryData(datavar)) {
            timeRadioButton.setEnabled(true);
            givenTimeText.setEditable(true);
        } else {
            timeRadioButton.setEnabled(false);
            givenTimeText.setEditable(false);
        }
        
        WinHelper.initTable(fixlistTable, new ArrayList<ExploredSymbol>());
    }//GEN-LAST:event_formComponentShown

    private void selectAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectAllButtonActionPerformed
        WinHelper.setListSelectall(simulationvarsList, "");
    }//GEN-LAST:event_selectAllButtonActionPerformed

    private void deselectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deselectButtonActionPerformed
        int[] selectedIndexes = new int[] {-1};
        simulationvarsList.setSelectedIndices(selectedIndexes);    
    }//GEN-LAST:event_deselectButtonActionPerformed

    private void confirmButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmButtonActionPerformed
        //generate plot command expression
        if (toPlotCommand()) {        
            //execute command
            this.setVisible(false);
            SimHyAHelper.executeCommand();
            //close this form
            this.dispose();
            //clear all form of plot
            WinHelper.closeFormAfterCommand();
        }
    }//GEN-LAST:event_confirmButtonActionPerformed

    private void addfixButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addfixButtonActionPerformed
        //show the form of adding fix
        WinHelper.showDialog(PublicParam.PlotNewFixForm, PlotNewFixForm.class);        
        //add fix variable
        fullFixTableModel = WinHelper.addVariableToFixList(fixlistTable);  
    }//GEN-LAST:event_addfixButtonActionPerformed

    public String getExceptExploredParam() {
        if (exploredparamsList.getSelectedValue() != null) {
            return exploredparamsList.getSelectedValue().toString();
        } else {
            return "";
        }
    }
    
    public String getSelectedFix() {
        if (fixlistTable.getRowCount() > 0 && fixlistTable.getSelectedRow() < 0) {
            //select the last row
            int selectedRowIndex = fixlistTable.getRowCount() - 1;
            fixlistTable.setRowSelectionInterval(selectedRowIndex, selectedRowIndex);
        }
        
        if (fixlistTable.getSelectedRow() >= 0) {
            return ((DefaultTableModel)fixlistTable.getModel()).getValueAt(fixlistTable.getSelectedRow(), 1).toString();
        } else {
            return "";
        }
    }
    
    private void helpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpButtonActionPerformed
        WinHelper.showHelp("plot/plot(timetrace)");
    }//GEN-LAST:event_helpButtonActionPerformed

    private void exploredparamsListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exploredparamsListMouseClicked
        //get slelected explored param
        String selectedParam = exploredparamsList.getSelectedValue().toString();
        //remove selected expored param from fixlist
        WinHelper.refreshItemOfFixList(fixlistTable, fullFixTableModel, selectedParam); 
    }//GEN-LAST:event_exploredparamsListMouseClicked

    private void finalStateRadioButtonItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_finalStateRadioButtonItemStateChanged
        givenTimeText.setEnabled(!finalStateRadioButton.isSelected());
    }//GEN-LAST:event_finalStateRadioButtonItemStateChanged

    private void timeRadioButtonItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_timeRadioButtonItemStateChanged
        givenTimeText.setEnabled(timeRadioButton.isSelected());
    }//GEN-LAST:event_timeRadioButtonItemStateChanged
    
    boolean toPlotCommand() {
        if (exploredparamsList.getSelectedValues().length == 0) {
            JOptionPane.showMessageDialog(this, "explored params(x) can't be empty!");     
            return false;
        }
        
        String s = "";
        //vars
        if (simulationvarsList.getSelectedValues().length > 0) {
            s += ",vars=[";
            for (int i = 0; i < simulationvarsList.getSelectedValues().length; i++) {
                if (i > 0) s += ",";
                s += simulationvarsList.getSelectedValues()[i].toString();
            }
            s += "]";
        }
                
        //time
        if (finalStateRadioButton.isSelected()) {
            s += ",time=final";
        } else if (timeRadioButton.isSelected() && givenTimeText.getText().length() > 0) {
            s += ",time=" + givenTimeText.getText();
        }
        
        //fix
        String fix = "";
        TableModel tm = fixlistTable.getModel();
        for (int i = 0; i < tm.getRowCount(); i++) {
            if (Boolean.valueOf(tm.getValueAt(i, 0).toString())) {
                if (tm.getValueAt(i, 1).toString().length() > 0 
                        && tm.getValueAt(i, 2).toString().length() > 0) {
                    //pname=pvalue
                    if (fix.length() > 0) fix += ",";
                    fix += tm.getValueAt(i, 1).toString() + "=[" + tm.getValueAt(i, 2).toString() + "]";
                }
            }
        }
        if (fix.length() > 0) s += ",fix=[" + fix + "]";
        
        //x-axis(explored params)
        if (exploredparamsList.getSelectedValues().length > 0) {
            s += ",x=";
            for (int i = 0; i < exploredparamsList.getSelectedValues().length; i++) {
                if (i > 0) s += ",";
                s += exploredparamsList.getSelectedValues()[i].toString();
            }
        }
        
        PublicParam.SimHyACommandExpression += s + ")";
        PublicParam.CommandTypeName = "Plot";    
        
        JOptionPane.showMessageDialog(this, PublicParam.SimHyACommandExpression);     
        
        return true;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PlotDetermForm dialog = new PlotDetermForm(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addfixButton;
    private javax.swing.JButton backButton;
    private javax.swing.JButton confirmButton;
    private javax.swing.JButton deselectButton;
    private javax.swing.JList exploredparamsList;
    private javax.swing.JRadioButton finalStateRadioButton;
    private javax.swing.JTable fixlistTable;
    private javax.swing.JTextField givenTimeText;
    private javax.swing.JButton helpButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton selectAllButton;
    private javax.swing.JList simulationvarsList;
    private javax.swing.JRadioButton timeRadioButton;
    // End of variables declaration//GEN-END:variables
    private String lastDataVariable = "";
    private DefaultTableModel fullFixTableModel;
}
